{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from IPython.core.interactiveshell import InteractiveShell\n",
    "InteractiveShell.ast_node_interactivity = 'all'  # default is ‘last_expr'\n",
    "\n",
    "%load_ext autoreload\n",
    "%autoreload 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "from azure.cosmos.cosmos_client import CosmosClient"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Upsert items\n",
    "\n",
    "This notebook is used to update or add an item to the `datasets` table."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Connect to the Cosmos DB instance\n",
    "\n",
    "`COSMOS_ENDPOINT` and `COSMOS_WRITE_KEY` need to be environment variables. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize Cosmos DB client\n",
    "url = os.environ['COSMOS_ENDPOINT']\n",
    "key = os.environ['COSMOS_WRITE_KEY']\n",
    "client = CosmosClient(url, credential=key)\n",
    "\n",
    "database = client.get_database_client('camera-trap')\n",
    "container_datasets = database.get_container_client('datasets')\n",
    "container_sequences = database.get_container_client('sequences')  # not used here"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Upsert an item\n",
    "in the `datasets` container.\n",
    "\n",
    "When you're *updating* an existing item instead of *inserting* a new item, you need to find its `id` and include it in the `item_to_update`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "# dict-like object representing the item to update or insert\n",
    "item_to_upsert = {\n",
    "    \"access\": [\n",
    "      \"internal\"\n",
    "    ],\n",
    "    \"comment\": \"...\",\n",
    "    \"container\": \"container_name\",\n",
    "    \"container_sas_key\": \"...\",\n",
    "    \"dataset_name\": \"dataset_name\",\n",
    "    \"path_prefix\": \"prefix\",\n",
    "    \"storage_account\": \"storage_account\"\n",
    "  }"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%time\n",
    "\n",
    "container_datasets.upsert_item(item_to_upsert)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Check that the `datasets` table is updated. \n",
    "\n",
    "The view in the Data Explorer on Azure Portal will remain outdated for a while it seems..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Length of results: 22\n",
      "CPU times: user 5.71 ms, sys: 1.66 ms, total: 7.37 ms\n",
      "Wall time: 113 ms\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "\n",
    "query = '''SELECT * FROM datasets d'''\n",
    "\n",
    "result_iterable = container_datasets.query_items(query=query, enable_cross_partition_query=True)\n",
    "\n",
    "datasets = {i['dataset_name']:{k: v for k, v in i.items() if not k.startswith('_')} for i in iter(result_iterable)}\n",
    "\n",
    "print('Length of results:', len(datasets))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "22"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(datasets)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python [conda env:cameratraps] *",
   "language": "python",
   "name": "conda-env-cameratraps-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
